<script>
  import config from './config'
  import store from '@/store'
  import { getToken } from '@/utils/auth'
  import { getNewAppVersion } from '@/api/login'

  export default {
    onLaunch: function() {
      this.initApp()
    },
    methods: {
      // 初始化应用
      initApp() {
        // 初始化应用配置
        this.initConfig()
        // 检查用户登录状态
        //#ifdef H5
        this.checkLogin()
        //#endif
		this.getAppVersion()
      },
      initConfig() {
        this.globalData.config = config
      },
      checkLogin() {
        if (!getToken()) {
          this.$tab.reLaunch('/pages/login') 
        }
      },
	  // 检查版本信息
	  getAppVersion(){
		let _this = this
		plus.runtime.getProperty(plus.runtime.appid,function(info){
			getNewAppVersion().then(res => {
				if(info.version && res.data.versionNumber){
					if (_this.compareVer(res.data.versionNumber, info.version)){
						uni.getSystemInfo({
							success() {
								uni.showLoading({
									title: '下载最新版本中。',
									mask: true,
								})
								uni.downloadFile({
									url: config.baseUrl + res.data.fileUrl,
									success(response) {
										if (response.statusCode === 200) {
											//console.log('下载成功', response)
											uni.hideLoading()
											plus.runtime.install(plus.io.convertLocalFileSystemURL(response
												.tempFilePath), {}, {}, function (error) {
													uni.showToast({
														title: '安装失败',
														duration: 1500,
													})
												})
										} else {
											uni.showToast({
												title: '下载失败',
												duration: 1500,
											})
										}
									},
								})
							}
						})
					}
				}
			})
		})
	  },
	  
	  // 版本比较 如果有最新版则返回true 反之则返回false
	  compareVer(remoteVer, localVer) {
	  	const rv = Number(remoteVer.replace(/\./g, ''))
	  	const lv = Number(localVer.replace(/\./g, ''))
	  	if (rv > lv) {
	  		return true
			console.log("有新版本")
	  	} else {
	  		return false
	  	}
	  },
    }
  }
</script>

<style lang="scss">
  @import '@/static/scss/index.scss'
</style>
